package com.kwok.rbac.application.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.kwok.rbac.application.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMVCConfig implements WebMvcConfigurer {

    @Autowired
    private TokenInterceptor tokenInterceptor;

    //SpringBoot统一解决CORS跨域问题
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*") // 所有域
                .allowedHeaders("*") // 请求头中携带任意参数
                .allowCredentials(true) // 时是否允许浏览器读取response的内容
                .allowedMethods("GET", "POST", "DELETE", "PUT","OPTIONS") // 允许访问的请求方式
                .maxAge(3600); // 浏览器缓存大头兵结果的时间
    }

    //Token登录拦截器注册
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login");
    }

    /**
     * 创建一个消息转换器，设置使用FastJSON，然后放到IOC容器中
     * 因为SpringMVC默认使用Jackson来解析json数据，而Jackson在解析Map时不够灵活，所以需要替换掉Jackson为Fastjson
     */
    @Bean
    public HttpMessageConverters fastjsonHttpMessageConverters() {
        //创建FastJson消息转换器
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        //创建配置对象
        FastJsonConfig config = new FastJsonConfig();
        //配置序列化进行格式化json数据
        config.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //将此配置传给转换器
        converter.setFastJsonConfig(config);

        HttpMessageConverter con = converter;
        //通过构造方法传递对象
        return new HttpMessageConverters(con);
    }

}
